﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace DotNetStar.TheKing.Web.Admin.Controllers
{
    using DotNetStar.TheKing.Services;
    using Models;
    using Infrastructure;
    using Microsoft.AspNetCore.Authorization;

    [Area("admin")]
    [Authorize(Roles =RoleDefinition.ADMINISTRATOR)]
    public class HomeController : Controller
    {
        private UserService _userService;
        public HomeController(UserService userService)
        {
            _userService = userService;
        }

        public IActionResult Index()
        {
            return View();
        }
        [AllowAnonymous]
        public IActionResult Login()
        {
            if (User.Identity.IsAuthenticated && User.IsInRole(Roles.Administrator.ToString()))
            {
                return RedirectToAction("Index");
            }
            return View();
        }
        
        [HttpPost,AllowAnonymous]
        public async Task<IActionResult> Login(LoginViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return View(model);
            }
            var user = await _userService.GetUserAsync(model.UserName, model.Password);
            if (user == null)
            {
                ModelState.AddModelError("error", "账号或密码不正确");
                return View(model);
            }

            if (user.Role == Infrastructure.Roles.Administrator)
            {
                await HttpContext.SignInAsync(user);
                return RedirectToAction("Index");
            }
            ModelState.AddModelError("error", "你没有权限进入");
            return View(model);
        }
    }
}